<template>
  <lay-container fluid class="container-box">
    <!--查询条件-->
    <lay-card>
      <lay-form :model="searchModel" ref="searchForm" size="sm" labelWidth="80" class="search-form">
        <lay-form-item label="部门名称" prop="deptName" mode="inline" >
          <lay-input v-model="searchModel.deptName" placeholder="请输入" allowClear />
        </lay-form-item>

        <lay-form-item label="上级部门" prop="parentId" mode="inline" >
          <lay-tree-select v-model="searchModel.parentId" :data="treeSelectDataSource"/>
        </lay-form-item>

        <lay-form-item mode="inline" v-permission="['biz:dept:list']">
          <lay-button type="primary" @click="search" prefix-icon="layui-icon-search">
            查询
          </lay-button>
          <lay-button @click="searchReset" prefix-icon="layui-icon-refresh">
            重置
          </lay-button>
        </lay-form-item>
      </lay-form>

      <!-- table表格 -->
      <div class="table-box">
        <lay-table
            :page="page"
            :columns="columns"
            :id="id"
            :loading="loading"
            :default-toolbar="['filter','print']"
            :data-source="dataSource"
            :autoColsWidth="true"
            :resize="true"
            :default-expand-all="expandAllFlag"
            :expand-index="1"
            v-model:selected-key="selectedKey"
            @change="search"
            @sortChange="sortChange">

          <!--操作列-->
          <template v-slot:operator="{ row }">
            <lay-space>
              <lay-button v-permission="['biz:dept:info']" @click="toInfo(row)" prefix-icon="layui-icon-tips" type="normal" size="sm">
                详情
              </lay-button>
              <lay-dropdown updateAtScroll>
                <lay-button type="primary" suffix-icon="layui-icon-down" size="sm">更多</lay-button>
                <template #content>
                  <lay-dropdown-menu>
                    <lay-dropdown-menu-item v-permission="['biz:dept:edit']" @click="toSave('编辑', row)">
                      <template #prefix><lay-icon type="layui-icon-edit"/></template>
                      <template #default>编辑</template>
                    </lay-dropdown-menu-item>
                    <lay-dropdown-menu-item v-permission="['biz:dept:remove']" @click="remove(row)">
                      <template #prefix><lay-icon type="layui-icon-delete"/></template>
                      <template #default>删除</template>
                    </lay-dropdown-menu-item>
                  </lay-dropdown-menu>
                </template>
              </lay-dropdown>
            </lay-space>
          </template>

          <!--工具栏-->
          <template v-slot:toolbar>
            <lay-button v-permission="['biz:dept:add']" @click="toSave('新增')" type="primary" size="sm">
              <lay-icon class="layui-icon-addition"/>
              新增
            </lay-button>
            <lay-button v-permission="['biz:dept:export']" @click="exportData" size="sm">
              <lay-icon class="layui-icon-export"/>
              导出
            </lay-button>
            <lay-button @click="expandAllToggle" size="sm" >
              {{ expandAllFlag ? '收起全部':'全部展开'}}
            </lay-button>
          </template>
        </lay-table>
      </div>
    </lay-card>

    <!-- 保存窗口 -->
    <lay-layer v-model="visibleSaveLayer" :title="saveLayerTitle" :btn="saveLayerBtn" :area="['730px', '300px']" :maxmin="true">
        <lay-form class="model-form" :model="saveModel" ref="saveForm" :rules="saveFormRules" size="sm" label-width="80">
          <lay-form-item label="部门名称" prop="deptName" mode="inline" >
            <lay-input v-model="saveModel.deptName" placeholder="请输入" allowClear   :required="true"/>
          </lay-form-item>

          <lay-form-item label="上级部门" prop="parentId" mode="inline" >
            <lay-tree-select v-model="saveModel.parentId" :data="treeSelectDataSource"  :required="true"/>
          </lay-form-item>

          <lay-form-item label="备注" prop="remark" mode="inline" >
            <lay-input v-model="saveModel.remark" placeholder="请输入" allowClear  />
          </lay-form-item>

        </lay-form>
    </lay-layer>

    <!-- 详情窗口 -->
    <lay-layer v-model="visibleInfoLayer" title="详情" :btn="infoLayerBtn" :area="['730px', '350px']" :maxmin="true" >
        <lay-form class="model-form" :model="infoModel" size="sm" label-width="100" :pane="true">

          <lay-form-item label="id" prop="id" mode="inline" >
              <lay-input v-model="infoModel.id" readonly />
          </lay-form-item>

          <lay-form-item label="部门名称" prop="deptName" mode="inline" >
              <lay-input v-model="infoModel.deptName" readonly />
          </lay-form-item>

          <lay-form-item label="上级部门" prop="parentName" mode="inline" >
              <lay-input v-model="infoModel.parentName" readonly />
          </lay-form-item>

          <lay-form-item label="创建时间" prop="createTime" mode="inline" >
              <lay-input v-model="infoModel.createTime" readonly />
          </lay-form-item>

          <lay-form-item label="备注" prop="remark" mode="inline" >
              <lay-input v-model="infoModel.remark" readonly />
          </lay-form-item>
        </lay-form>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">

  import { ref, reactive ,onMounted} from 'vue'
  import { layer} from '@layui/layui-vue'
  import { treeListApi,treeApi,saveApi,removeApi,infoApi,exportApi} from '../../../api/module/system/sys-dept'
  import { Rules} from 'async-validator';

  //加载函数
  onMounted(() => {
    //查询树下拉框数据
    loadTreeSelectData();
    //查询数据
    search();
  })

  //主键id
  const id = ref<string>("id")
  //表格数据源
  const dataSource = ref<any[]>([])
  //树下拉框数据源
  const treeSelectDataSource = ref<any[]>([])
  //是否展开
  const expandAllFlag = ref<boolean>(false)
  //选中数据行id
  const selectedKey = ref<string>()
  //表格是否加载中
  const loading = ref<boolean>(false)
  //保存表单
  const saveForm = ref<any>()
  //查询条件表单
  const searchForm = ref<any>()
  //是否显示更新窗口
  const visibleSaveLayer = ref<boolean>(false)
  //是否显示详情窗口
  const visibleInfoLayer = ref<boolean>(false)
  //新增/编辑窗口标题
  const saveLayerTitle = ref<string>()
  //查询条件数据
  const searchModel = ref<any>({})
  //保存数据
  const saveModel = ref<any>({})
  //详情数据
  const infoModel = ref<any>({})

  //分页参数数据
  const page = reactive<any>({
    current: 1,
    limit: 10,
    total: 0
  })

  //排序参数数据
  const sortQuery = reactive<any>({
    sortField:'createTime',
    sortType:'desc'
  })

  //表格字段
  const columns = ref<any[]>([
    { title: 'ID', width: '60px', key: 'id', ellipsisTooltip:"true"},
    { title: '部门名称', width: '80px',key: 'deptName',ellipsisTooltip:"true",sort: 'desc'},
    { title: '上级部门', width: '80px',key: 'parentId',ellipsisTooltip:"true",hide: "true"},
    { title: '显示顺序', width: '80px',key: 'orderNum',ellipsisTooltip:"true",hide: "true"},
    { title: '删除标志', width: '80px',key: 'delFlag',ellipsisTooltip:"true",hide: "true"},
    { title: '备注', width: '80px',key: 'remark',ellipsisTooltip:"true"},
    { title: '创建人姓名', width: '80px',key: 'createUserName',ellipsisTooltip:"true",hide: "true"},
    { title: '创建时间', width: '80px',key: 'createTime',ellipsisTooltip:"true",sort: 'desc'},
    { title: '修改人姓名', width: '80px',key: 'updateUserName',ellipsisTooltip:"true",hide: "true"},
    { title: '更新时间', width: '80px',key: 'updateTime',ellipsisTooltip:"true",hide: "true"},
    { title: '操作', width: '100px', key: 'operator',fixed: 'right',customSlot: 'operator'}
  ])

  //保存表单验证规则
  const saveFormRules = ref<Rules>({
    deptName : {
      type :  'string',
      min : 1,
      max : 50
    },
    parentId : {
      type :  'string',
      min : 1,
      max : 20
    },
  })

  //保存窗口按钮
  const saveLayerBtn = ref([{
    text: "提交",
    callback: () => {
      //提交要保存的数据
      saveForm.value.validate((isValidate: any, model: any, errors: any) => {
        if(!isValidate){
          return;
        }
        saveApi(model).then(({ data, code, msg }) => {
          if (code == 200) {
            visibleSaveLayer.value = false
            search();
          }
        })
      })
    }
  },{
    text: "取消",
    callback: () => {
      //关闭保存窗口
      saveForm.value.reset()
      visibleSaveLayer.value = false
    }
  }])

  //详情窗口按钮
  const infoLayerBtn = ref([{
    text: "关闭",
    callback: () => {
      //详情窗口关闭
      visibleInfoLayer.value = false
    }
  }])

  //查询数据
  const search = async() => {
    loading.value = true
    await loadDataSource();
    loading.value = false
  }

  //排序查询
  const sortChange = (sortField: string, sortType: string) => {
    if(sortType){
      sortQuery.sortField = sortField;
      sortQuery.sortType = sortType;
      //查询数据
      search();
    }
  }

  //展开/收起列表
  const expandAllToggle = function() {
    expandAllFlag.value = !expandAllFlag.value;
  }

  //导出数据
  const exportData = () => {
    loading.value = true
    exportApi(Object.assign(searchModel.value,sortQuery));
    loading.value = false
  }

  //清除查询条件
  const searchReset = () => {
    searchForm.value.reset();
  }

  //显示保存窗口
  const toSave = (text: any, row?: any) => {
    saveLayerTitle.value = text
     //刷新下拉框树
     loadTreeSelectData()
    if (row) {
      infoApi(row.id)
      .then(({ data, code, msg }) => {
          if (code == 200) {
            saveModel.value = data;
            //显示保存窗口
            visibleSaveLayer.value = true
          }
        })
       
    } else {
      saveModel.value = {}
      //显示保存窗口
      visibleSaveLayer.value = true
    }

  }

  //显示详情窗口
  const toInfo = (row: any) =>{
    infoApi(row.id)
      .then(({ data, code, msg }) => {
        if (code == 200) {
          infoModel.value = data;
          visibleInfoLayer.value = true
        }
      })
  }

  //加载表格数据
  const loadDataSource = () => {
    return new Promise<void>((resolve) => {
        treeListApi(Object.assign(searchModel.value,sortQuery))
          .then(({ data, code, msg }) => {
            if (code == 200) {
              dataSource.value = data;
            }
          }).finally(()=>{
        resolve();
      })
    })
  }

  //加载树下拉框数据
  const loadTreeSelectData = () => {
    treeApi(searchModel.value)
      .then(({data, code, msg}) => {
        if (code == 200) {
          treeSelectDataSource.value = data;
          console.log("treeSelectDataSource",treeSelectDataSource);
          
        }
      })
  }

  //删除数据
  const remove = (row:any) => {
    layer.confirm(`确认删除此数据？`, {
      title: '提示',
      btn: [{
        text: '确定',
        callback: (id: any) => {
          removeApi(row.id).then(({ data, code, msg }) => {
            if (code == 200) {
              layer.msg('删除成功!')
              layer.close(id)
              search();
            }
          })
        }
      },{
        text: '取消',
        callback: (id: any) => {
          layer.close(id)
        }
      }]
    })
  }

</script>

<style scoped>

</style>